package com.ease.business.systemmonitor.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import com.ease.business.systemmonitor.constant.BaseConstant;
import com.ease.business.systemmonitor.constant.EmptyObjectConstant;
import com.ease.model.systemmonitor.UnixServer;

public class ServerInfoUtil {

	public static UnixServer getHostPerformance(String ip, String userName, String password) throws Exception {
		Connection conn = null;
		try {
			conn = new Connection(ip);
			conn.connect(null, 2000, 2000);
			boolean isAuthenticated = conn.authenticateWithPassword(userName, password);
			if (!isAuthenticated) {
				throw new Exception("SSH authentication failed with [ userName: " + userName + ", password: " + password + "]");
			}
			UnixServer localHostPerformanceEntity = getHostPerformance(conn);
			return localHostPerformanceEntity;
		} catch (Exception e) {
			throw new Exception("SSH 连接错误", e);
		} finally {
			if (null != conn)
				conn.close();
		}

	}

	private static UnixServer getHostPerformance(Connection conn) throws Exception {
		UnixServer systemPerformanceEntity = null;
		Session session = null;
		BufferedReader read = null;
		try {
			systemPerformanceEntity = new UnixServer();
			// systemPerformanceEntity.setIp(conn.getHostname());
			session = conn.openSession();
			session.execCommand("top -b -n 1 | head -5");
			read = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
			String line = "";
			int lineNum = 0;
			String totalMem = EmptyObjectConstant.EMPTY_STRING;
			String freeMem = EmptyObjectConstant.EMPTY_STRING;
			String buffersMem = EmptyObjectConstant.EMPTY_STRING;
			String cachedMem = EmptyObjectConstant.EMPTY_STRING;
			while ((line = read.readLine()) != null) {
//				if (line == null)
//					continue;
				lineNum++;
				if (5 < lineNum) {
					UnixServer localHostPerformanceEntity1 = systemPerformanceEntity;
					return localHostPerformanceEntity1;
				}
				if (1 == lineNum) {
					int loadAverageIndex = line.indexOf("load average: ");
					String loadAverages = line.substring(loadAverageIndex).replace("load average: ", EmptyObjectConstant.EMPTY_STRING);
					String[] loadAverageArray = loadAverages.split(",");
					if (3 != loadAverageArray.length)
						continue;
					systemPerformanceEntity.setLoad(loadAverageArray[0].trim());
					continue;
				}
				if (3 == lineNum) {
					String cpuUsage = line.split(",")[0].replace("Cpu(s):", EmptyObjectConstant.EMPTY_STRING).replace("us", EmptyObjectConstant.EMPTY_STRING);
					systemPerformanceEntity.setCpuUsage(cpuUsage.trim());
					continue;
				}
				if (4 == lineNum) {
					String[] memArray = line.replace("Mem:", EmptyObjectConstant.EMPTY_STRING).split(",");
					totalMem = (memArray[0].replace("total", EmptyObjectConstant.EMPTY_STRING)).trim().replace("k", EmptyObjectConstant.EMPTY_STRING);
					freeMem = (memArray[2].replace("free", EmptyObjectConstant.EMPTY_STRING)).trim().replace("k", EmptyObjectConstant.EMPTY_STRING);
					buffersMem = (memArray[3].replace("buffers", EmptyObjectConstant.EMPTY_STRING)).trim().replace("k", EmptyObjectConstant.EMPTY_STRING);
					continue;
				}
				if (5 != lineNum)
					continue;
				String[] memArray = line.replace("Swap:", EmptyObjectConstant.EMPTY_STRING).split(",");
				cachedMem = (memArray[3].replace("cached", EmptyObjectConstant.EMPTY_STRING)).trim().replace("k", EmptyObjectConstant.EMPTY_STRING);

				if (new String[] { totalMem, freeMem, buffersMem, cachedMem }.length == 0 || new String[] { totalMem, freeMem, buffersMem, cachedMem } == null) {
					throw new Exception("Error when get system performance of ip: " + conn.getHostname() + ", can't get totalMem, freeMem, buffersMem or cachedMem");
				}

				Double totalMemDouble = Double.valueOf(Double.parseDouble(totalMem));
				Double freeMemDouble = Double.valueOf(Double.parseDouble(freeMem));
				Double buffersMemDouble = Double.valueOf(Double.parseDouble(buffersMem));
				Double cachedMemDouble = Double.valueOf(Double.parseDouble(cachedMem));

				Double memoryUsage = Double.valueOf(1.0D - (freeMemDouble.doubleValue() + buffersMemDouble.doubleValue() + cachedMemDouble.doubleValue()) / totalMemDouble.doubleValue());
				systemPerformanceEntity.setMemoryUsage(memoryUsage.doubleValue() * 100.0D + "%");
			}
			Object diskUsageMap = new HashMap();
			session = conn.openSession();
			session.execCommand("df -lh");
			read = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
			boolean isFirstLine = true;
			while ((line = read.readLine()) != null) {
				if (isFirstLine) {
					isFirstLine = false;
					continue;
				}
				if (line == null || line.length() == 0) {
					continue;
				}
				line = line.replaceAll(" {1,}", BaseConstant.WORD_SEPARATOR);
				String[] lineArray = line.split(BaseConstant.WORD_SEPARATOR);
				if (6 != lineArray.length) {
					continue;
				}
				String diskUsage = lineArray[4];
				String mountedOn = lineArray[5];
				((Map) diskUsageMap).put(mountedOn, diskUsage);
			}
			systemPerformanceEntity.setDiskUsage(((Map) diskUsageMap).toString());

		} catch (Exception e) {
			throw new Exception("Error when get system performance of ip: " + conn.getHostname(), e);
		} finally {
			try {
				if (null != read)
					read.close();
				if (null != session)
					session.close();
			} catch (Exception e) {
			}
		}
		return (UnixServer) systemPerformanceEntity;
	}

	public static void main(String[] args) throws Exception {
		System.out.print(getHostPerformance("192.168.0.130", "root", "-['/0p;."));
	}
}
